var express = require('express')
var jwt = require('jsonwebtoken')
var fs = require('fs')
var path = require('path')
const { hasUncaughtExceptionCaptureCallback } = require('process')

var user = express.Router()

//登录用户数据库
let lujing_admin

let conment_admin
function admin () {
    lujing_admin = path.join( __dirname , '../admin.json')
    conment_admin = fs.readFileSync(lujing_admin)
    conment_admin = conment_admin.toString() ? JSON.parse(conment_admin) : []
}

//数据数据库
let conment_user
let lujing_user
function user_con () {
    lujing_user = path.join( __dirname , '../user.json')
    conment_user = fs.readFileSync(lujing_user)
    conment_user = conment_user.toString() ? JSON.parse(conment_user) : []
}

//token唯一
let token

//登录
user.get('/enroll' , (req , res) => {
    admin()
    var {username , pass} = req.query
    var index = conment_admin.findIndex((item)=> {
        return item.username == username && item.pass == pass
    })
    if( index != -1){
        token = jwt.sign({username} , '111' , {algorithm : 'HS256' , expiresIn : '2d'})
        res.send({code:200 , mas:'登陆成功' , token : token})
    }else{
        res.send({code:400 , mas:'登陆失败'})
    }
})

//注册
user.post('/zhuce' , (req , res) => {
    admin()
    var {username , pass} = req.body
    var index = conment_admin.findIndex((item) => {
        return item.username == username
    })
    if( index == -1){
        token = jwt.sign({username} , '111' , {algorithm : 'HS256' , expiresIn : '2d'})
        res.send({code:200 , mas:'注册成功' , token : token})
        conment_admin.push({...req.body})
        fs.writeFileSync(lujing_admin , JSON.stringify(conment_admin) , 'utf8')
    }else{
        res.send({code:400 , mas:'注册失败'})
    }
})

//添加数据库
user.post( '/adduser' , (req , res) => {
    user_con()
    conment_user.push({...req.body , status : true })
    fs.writeFileSync(lujing_user, JSON.stringify(conment_user) , 'utf8')
    res.send({code:200 , mas : '添加成功'})
})

//获取数据
user.get( '/render' , (req , res) => {
    user_con()
    var {page , count} = req.query
    var arr = conment_user.slice((page - 1) * count , count * page)
    res.send({code:200 , list:arr ,lengths : arr.length})
})

//删除
user.post('/delete' , (req , res) => {
    var {name} = req.body
    user_con()
    var index = conment_user.findIndex((item) => {
        return item.name == name
    })
    conment_user.splice(index , 1)
    fs.writeFileSync(lujing_user , JSON.stringify(conment_user) , 'utf8')
    var num = parseInt((index + 1 )/ 3)
    if(num < 1){num = 1}
    res.send({code:200 , num : num , list:conment_user})

})

//查询
user.get('/sousuo' , (req , res) => {
    var {name} = req.query
    user_con()
    
    var newarr = []
    conment_user.forEach((item) => {
        item.name.includes(name) ? newarr.push(item) : null
    });

    res.send({list:newarr})

})

module.exports = user;